package icasue.net.base.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2021/4/8 下午5:41
 * @UpdateDate:
 * @Description:
 */
public class IOUtil {

    public static byte[] read(InputStream inStream, char end, char... ignores) throws IOException {
        if(inStream == null){
            return new byte[0];
        }
        boolean existIgnoreChars = ignores != null ? true : false;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int intVal = -1;
        while ((intVal = inStream.read()) != -1 && intVal != end){
            if(existIgnoreChars) {
                for (char ignore : ignores) {
                    char chrVal = (char) intVal;
                    if (ignore == chrVal) {
                        intVal = -1;
                    }
                }
            }
            if(intVal != -1){
                outputStream.write(intVal);
            }
        }
        return outputStream.toByteArray();
    }

    public static String read(InputStream inStream, Charset charset, char end, char... ignores) throws IOException {
        byte[] res = read(inStream, end, ignores);
        charset = charset == null ? Charset.defaultCharset() : charset;
        return new String(res,charset);
    }

    public static byte[] readLine(InputStream inputStream) throws IOException {
        int intVal = -1;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        while ((intVal = inputStream.read()) != -1 && intVal != '\n'){
            if('\r' != intVal){
                outputStream.write(intVal);
            }
        }
        return outputStream.toByteArray();
    }

    public static byte[] readLine(InputStream inStream,char... ignores) throws IOException {
        return read(inStream,'\n',ignores);
    }

    public static String readLine(InputStream inStream, Charset charset, char... ignores) throws IOException {
        byte[] res = read(inStream, '\n', ignores);

        return new String(res,charset);
    }

    public static byte[] readLength(InputStream inStream, int length) throws IOException {
        byte[] res = new byte[length];
        int off = 0;
        int len = length;

        while (len > 0){
            int curReadLen = inStream.read(res, off, len);
            if(curReadLen == -1){
                throw new IOException("EOF");
            }
            off += curReadLen;
            len -= curReadLen;
        }
        return res;
    }
}
